import type { AuthApi } from '#/api/core/model/userModel'

import { ref } from 'vue'
import { useRouter } from 'vue-router'

import { DEFAULT_HOME_PATH, LOGIN_PATH } from '#/config'
import { resetAllStores, useAccessStore, useUserStore } from '@vben/stores'

import { notification } from 'ant-design-vue'
import { defineStore } from 'pinia'

import { fetchLogin, getUserInfoApi } from '#/api'
import { $t } from '#/locales'

export const useAuthStore = defineStore('auth', () => {
    const accessStore = useAccessStore()
    const userStore = useUserStore()
    const router = useRouter()
    const loginLoading = ref(false)

    function transformUserInfo(userInfo: AuthApi.GetUserInfoModel) {
        return {
            /**
             * 头像
             */
            avatar: userInfo.avatar,
            /**
             * 用户昵称
             */
            realName: userInfo.realname,
            /**
             * 用户角色
             */
            roles: userInfo.roles,
            /**
             * 用户id
             */
            userId: userInfo.id,
            /**
             * 用户名
             */
            username: userInfo.nickname,
            rolesVo: userInfo.rolesVo
        }
    }

    async function fetchUserInfo() {
        let userInfo: AuthApi.GetUserInfoModel | null = null
        userInfo = await getUserInfoApi()
        userStore.setUserInfo(transformUserInfo(userInfo))
        accessStore.setAccessCodes(userInfo.permissionList)
        return userInfo
    }

    /**
     * 异步处理登录操作
     * Asynchronously handle the login process
     * @param params 登录表单数据
     */
    async function authLogin(
        params: AuthApi.LoginCodeParams | AuthApi.LoginParams,
        onSuccess?: () => Promise<void> | void
    ) {
        // 异步处理用户登录操作并获取 accessToken
        let userInfo: AuthApi.GetUserInfoModel | null = null
        try {
            loginLoading.value = true
            const res = await fetchLogin(params)

            const { access_token: accessToken } = res

            // 如果成功获取到 accessToken
            if (accessToken) {
                accessStore.setAccessToken(accessToken)

                // 获取用户信息并存储到 accessStore 中
                const fetchUserInfoResult = await fetchUserInfo()

                userInfo = fetchUserInfoResult

                const accessCodes = userInfo.permissionList

                userStore.setUserInfo(transformUserInfo(userInfo))
                accessStore.setAccessCodes(accessCodes)

                if (accessStore.loginExpired) {
                    accessStore.setLoginExpired(false)
                } else {
                    onSuccess ? await onSuccess?.() : await router.push(DEFAULT_HOME_PATH)
                }

                if (userInfo?.nickname) {
                    notification.success({
                        description: `${$t('authentication.loginSuccessDesc')}:${userInfo?.nickname}`,
                        duration: 3,
                        message: $t('authentication.loginSuccess')
                    })
                }
            }
        } finally {
            loginLoading.value = false
        }

        return {
            userInfo
        }
    }

    async function logout(redirect: boolean = true) {
        resetAllStores()
        accessStore.setLoginExpired(false)

        // 回登录页带上当前路由地址
        await router.replace({
            path: LOGIN_PATH,
            query: redirect
                ? {
                      redirect: encodeURIComponent(router.currentRoute.value.fullPath)
                  }
                : {}
        })
    }

    function $reset() {
        loginLoading.value = false
    }

    return {
        $reset,
        authLogin,
        fetchUserInfo,
        loginLoading,
        logout
    }
})
